package main

import (
	"fmt"
	"os/exec"
	"regexp"
	"strings"
)

func main() {
	output, err := exec.Command("ip", "route").Output()
	if err != nil {
		fmt.Println(err)
		return
	}
	//	output := `default via 100.114.197.98 dev usb0
	//default via 172.168.3.253 dev wlan0 proto dhcp metric 600
	//100.114.197.0/24 dev usb0 proto kernel scope link src 100.114.197.97
	//172.17.0.0/16 dev docker0 proto kernel scope link src 172.17.0.1 linkdown
	//172.18.39.0/24 dev br0 proto kernel scope link src 172.18.39.100
	//172.168.3.0/24 dev wlan0 proto kernel scope link src 172.168.3.236 metric 600
	//192.168.1.0/24 dev br1 proto kernel scope link src 192.168.1.2 linkdown
	//`
	gateway, err := extractDefaultGateway(string(output))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("gateway:", gateway)
}

func extractDefaultGateway(routeOutput string) (string, error) {
	// 按行分割路由表输出
	lines := strings.Split(routeOutput, "\n")

	for _, line := range lines {
		// 跳过非默认路由和空行
		if !strings.Contains(line, "default via") || len(strings.TrimSpace(line)) == 0 {
			continue
		}

		// 正则匹配：default via <IP> dev <Interface>
		re := regexp.MustCompile(`default via\s+([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3})\s+dev\s+usb0`)
		matches := re.FindStringSubmatch(line)
		if matches != nil {
			return matches[1], nil
		}

	}

	return "", fmt.Errorf("未找到匹配的默认路由条目")
}
